package tech.mhuang.pacebox.springboot.core.aop;

import lombok.Data;
import org.aopalliance.aop.Advice;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.framework.AopProxyFactory;
import org.springframework.aop.framework.DefaultAopProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

/**
 * 代理对象工厂类
 *
 * @author yuanhang.huang
 * @since 1.0.0
 */
@Data
public class AopProxyFactoryBean {

    private Object target;
    private Advice advice;
    private String expression;

    public <T> T getProxy(T target, Advice advice, String expression) {

        AopProxyFactory aopProxyFactory = new DefaultAopProxyFactory();
        AdvisedSupport advisedSupport = new AdvisedSupport();
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();

        pointcut.setExpression("execution(" + expression + ")");
        advisor.setPointcut(pointcut);
        advisor.setAdvice(advice);
        advisedSupport.addAdvisor(advisor);
        advisedSupport.setTarget(target);

        AopProxy aopProxy = aopProxyFactory.createAopProxy(advisedSupport);

        return (T) aopProxy.getProxy();

    }

    public <T> T getProxy() {
        return (T) getProxy(this.target, this.advice, this.expression);
    }


}
